﻿# -*- coding: utf-8 -*

import config
import datastore
import geo.geotypes
import distance

# csie building
def getHomeSpot():
    query = datastore.HotSpot.all()
    query.filter('name =', config.HOME_SPOT_NAME)
    home = query.fetch(1)[0]
    return home

# by walking
def getNearbyStops(location):
    box_offset = config.BOX_OFFSET
    while True:
        res = datastore.Stop.bounding_box_fetch(
            datastore.Stop.all(),
            geo.geotypes.Box(min(location.lat + box_offset, 90.0),
                             min(location.lon + box_offset, 180.0),
                             max(location.lat - box_offset, -90.0),
                             max(location.lon - box_offset, -180.0)),
            max_results=5)

        if len(res) > 0:
            return res
        elif box_offset < 180.0:
            box_offset *= config.BOX_OFFSET_MUL
        else:
            raise ValueError('no transportation location found')

# by walking
def isWalkable(location1, location2):
    box_offset = config.BOX_OFFSET
    boxUp = location1.lat + box_offset
    boxDown = location1.lat - box_offset
    boxLeft = location1.lon - box_offset
    boxRight = location1.lon + box_offset
    return (location2.lat <= boxUp and location2.lat >= boxDown and location2.lon >= boxLeft and location2.lon <= boxRight)
    
# by vehicle
def getNextPlans(stop):
    query = datastore.LineStop.all()
    query.filter('stop =', stop.key())
    nextPlans = query.fetch(1000)
    return nextPlans
    
# in minute
def getWalkingTime(geo1, geo2):
    dist = distance.Distance().getDistance(geo1.lat, geo1.lon, geo2.lat, geo2.lon)
    speed = 1.5 # 1.5 meters per second
    return dist / speed

# in minute
def getVehicleTime(stop1, stop2):
    return 2 # about 2 minutes... right?

def getPrice(stopStart, stopEnd, line):
    return 20
    query = datastore.MrtPrice.all().filter('stopStart =', stopStart).filter('stopEnd =', stopEnd)
    if query.count() == 0:
        query = datastore.MrtPrice.all().filter('stopStart =', stopEnd).filter('stopEnd =', stopStart)
        if query.count() == 0:
            raise ValueError('no price information for ' + stopStart.name.encode('utf-8') + \
                             ' and ' + stopEnd.name.encode('utf-8'))
    return query.fetch(1)[0].price
